// pages/Login/index.tsx
import { login as userLogin } from '@/services/user';
import { PermissionUtils } from '@/utils/permission';
import { RolePermissionVo } from '@/types/permission';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { Alert, Tabs, message } from 'antd';
import React, { CSSProperties, useState } from 'react';

type LoginType = 'account' | 'phone';

const LoginMessage: React.FC<{ content: string }> = ({ content }) => {
  return (
      <Alert
          style={{ marginBottom: 24 }}
          message={content}
          type="error"
          showIcon
      />
  );
};

const containerStyle: CSSProperties = {
  display: 'flex',
  flexDirection: 'column',
  height: '100vh',
  overflow: 'auto',
  backgroundImage:
      "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
  backgroundSize: '100% 100%',
};

export default function LoginPage() {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<LoginType>('account');
  const { setInitialState } = useModel('@@initialState');

  const handleSubmit = async (values: any) => {
    try {
      // 1. 执行登录 - 获取认证信息
      const loginRes = await userLogin({
        ...values,
        loginType: type === 'account' ? 1 : 2,
        phone: values.mobile || values.phone,
      } as API.LoginParams);

      if (loginRes.code === 200) {
        message.success('登录成功！');

        // 2. 保存认证信息
        if (loginRes.data?.token) {
          sessionStorage.setItem('token', loginRes.data.token);
        }

        try {
          // 3. 获取权限信息（使用缓存）
          const permissions: RolePermissionVo = await PermissionUtils.getUserPermissions();

          // 4. 获取用户基本信息
          const userInfo = loginRes?.data?.user || {};

          // 5. 设置完整的初始状态
          if (setInitialState) {
            await setInitialState({
              fetchUserInfo: async () => userInfo,
              fetchUserPermissions: async () => permissions,
              currentUser: {
                ...userInfo,
                permissions: permissions.userPermission,
                menus: permissions.menus,
              },
            });
          }
        } catch (error) {
          console.error('获取用户信息或权限失败:', error);
          message.error('获取用户信息失败，请刷新页面重试');

          // 即使部分信息获取失败，也设置基础信息
          const userInfo = loginRes?.data?.user || {};
          if (setInitialState) {
            await setInitialState({
              fetchUserInfo: async () => userInfo,
              fetchUserPermissions: async () => ({
                menus: [],
                userPermission: {
                  menuPermissions: [],
                  buttonPermissions: []
                }
              }),
              currentUser: {
                ...userInfo,
                permissions: {
                  menuPermissions: [],
                  buttonPermissions: []
                },
                menus: [],
              },
            });
          }
        }

        // 6. 跳转到目标页面
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }

      setUserLoginState(loginRes);
    } catch (error) {
      message.error('登录失败，请重试！');
    }
  };

  const { status, type: loginType } = userLoginState;

  return (
      <div style={containerStyle}>
        <div style={{ flex: '1', padding: '32px 0' }}>
          <LoginForm
              contentStyle={{ minWidth: 280, maxWidth: '75vw' }}
              logo={
                <img
                    alt="logo"
                    src="https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg"
                />
              }
              title="管理系统"
              subTitle="租赁管理系统"
              initialValues={{ autoLogin: true }}
              onFinish={async (values) => await handleSubmit(values)}
          >
            <Tabs
                activeKey={type}
                onChange={(key) => setType(key as LoginType)}
                centered
                items={[
                  {
                    key: 'account',
                    label: '账户密码登录',
                  },
                  {
                    key: 'phone',
                    label: '手机号登录',
                  },
                ]}
            />

            {status === 'error' && loginType === 'account' && (
                <LoginMessage content="账户或密码错误" />
            )}

            {type === 'account' && (
                <>
                  <ProFormText
                      name="account"
                      fieldProps={{ size: 'large', prefix: <UserOutlined /> }}
                      placeholder="请输入用户名"
                      rules={[{ required: true, message: '用户名是必填项！' }]}
                  />
                  <ProFormText.Password
                      name="password"
                      fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
                      placeholder="请输入密码"
                      rules={[{ required: true, message: '密码是必填项！' }]}
                  />
                </>
            )}

            {status === 'error' && loginType === 'phone' && (
                <LoginMessage content="验证码错误" />
            )}

            {type === 'phone' && (
                <>
                  <ProFormText
                      fieldProps={{ size: 'large', prefix: <UserOutlined /> }}
                      name="mobile"
                      placeholder="请输入手机号！"
                      rules={[
                        { required: true, message: '手机号是必填项！' },
                        { pattern: /^1\d{10}$/, message: '不合法的手机号！' },
                      ]}
                  />
                  <ProFormText
                      fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
                      name="captcha"
                      placeholder="请输入验证码！"
                      rules={[{ required: true, message: '验证码是必填项！' }]}
                  />
                </>
            )}

            <div style={{ marginBottom: 24 }}>
              <ProFormCheckbox noStyle name="autoLogin">
                自动登录
              </ProFormCheckbox>
              <a
                  style={{ float: 'right' }}
                  onClick={() => history.push('/find')}
              >
                忘记密码
              </a>
            </div>
          </LoginForm>
        </div>
      </div>
  );
}